package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.GlobalSettings;
import pl.edu.uj.tcs.blef.server.Table;

/**
 * Client-Server protocol request /create-table default handler.
 * @author Maciej Bendkowski
 *
 */
public final class CreateTableRequestHandler implements RequestHandler {
	
	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		CreateTableRequest ctr = (CreateTableRequest)request;
		try{
			
			Table t = GlobalSettings._MAIN_SERVER_.registryTable(ctr.getTableName(), ctr.getPlayerNick());
			String[] param = new String[1]; param[0] = "OK Table created at port " + t.getPort();
			Request r = new OKRequestFactory().build(param, new NullRequestHandler());
			r.send(new PrintWriter(socket.getOutputStream()));
			
		} catch(BussyServerException e){
			
			try{
				Request r = new BussyServerErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch(Exception ex) { }
			
		} catch(InvalidParametersException e){
			
			try{
				Request r = new InvalidParametersErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch(Exception ex) { }
			
		} catch(Exception ex) { }
	}
}
